<?php

namespace app\admin\service;
use app\admin\service\FieldSetService;
use app\admin\db\Field;

class FieldService
{
	
	/*
     * @Description  获取数据列表
	 * @param (输入参数：)  {array}        where 查询条件
	 * @param (输入参数：)  {int}          limit 分页参数
     * @param (输入参数：)  {String}       field 查询字段
     * @param (输入参数：)  {String}       orderby 排序字段
     * @return (返回参数：) {array}        分页数据集
	 */
	public static function pageList($where=[],$limit,$field="*",$orderby=''){
		
		try{
			$list = Field::loadList($where,$limit,$field,$orderby);
			$count = Field::countList($where);
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
			
		return ['list'=>$list,'count'=>$count];	
	}
	
	
	//添加
	public static function add($data){
	
		try{
			$data['config'] = str_replace('，',',',$data['config']);
			if($res = Field::createData($data)){
				Field::edit(['id'=>$res,'sortid'=>$res]);
				FieldSetService::createField($data);
			}
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
			
		return $reset;	
	}
	
	//修改
	public static function edit($data){
	
		try{
			$data['config'] = str_replace('，',',',$data['config']);
			$info = Field::getInfo($data['id']);
			if($data['field'] <> $info['field'] || $data['type'] <> $info['type']){
				FieldSetService::updateField($info,$data);
			}
			$reset = Field::edit($data);
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
			
		return $reset;	
	}
	
	//删除
	public static function delete($where){
	
		try{	
			$reset = Field::delete($where);
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
			
		return $reset;	
	}
	
	//排序上下移动
	public static function setSort($id,$type){
		$data = Field::getInfo($id);
		if($type == 1){
			$map['sortid']  = array('<',$data['sortid']);
			$map['extend_id'] = $data['extend_id'];
			$info = Field::getWhereInfo(formatWhere($map),'*',$order='sortid desc');
		}else{
			$map['sortid']  = array('>',$data['sortid']);
			$map['extend_id'] = $data['extend_id'];
			$info =	Field::getWhereInfo(formatWhere($map),'*',$order='sortid asc');
		}
		
		try{
			Field::edit(['id'=>$id,'sortid'=>$info['sortid']]);
			Field::edit(['id'=>$info['id'],'sortid'=>$data['sortid']]);
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
		
		return true;  
		
	}
	
	
	
}
